package com.rub.android.ui.activity

import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.rub.android.R
import com.rub.android.widget.InjectorUtil
import com.rub.android.dao.UserDao
import com.rub.android.extension.showToast
import com.rub.android.model.UserModel
import com.rub.android.utils.ResponseHandler
import com.rub.android.utils.logI
import com.rub.android.viewmodel.UserViewModel
import com.trello.rxlifecycle.components.support.RxAppCompatActivity
import kotlinx.android.synthetic.main.activity_login.*
import java.util.*

/**
 * https://www.jb51.net/article/196778.htm
 * https://blog.csdn.net/shenggaofei/article/details/105906872
 * https://blog.csdn.net/Afanbaby/article/details/75635249
 * https://blog.csdn.net/qq_29072049/article/details/108829453
 * https://icons8.com/icons/set/eye
 * https://www.jianshu.com/p/8fa6854566e9
 */
class LoginActivity : RxAppCompatActivity(), View.OnClickListener {
    private var imageView: ImageView? = null

    // 输入框密码是否是隐藏的，默认为true
    private var isHideFirst = true
    private lateinit var userName: EditText
    private lateinit var passWord: EditText

    private val viewModel by lazy {
        ViewModelProvider(
            this,
            InjectorUtil.getUserViewModelFactory()
        ).get(UserViewModel::class.java)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        imageView = findViewById(R.id.iv_eye)
        passWord = findViewById(R.id.et_pass_word)
        userName = findViewById(R.id.et_user_name)

        imageView?.setOnClickListener(this)
        imageView?.setImageResource(R.drawable.hide_eye)

        checkArgs()
        btnLogin()

    }

    private fun btnLogin() {
        btn_login.setOnClickListener {
            viewModel.login(userName.text.toString(), passWord.text.toString())
            observe()
        }
    }

    /**
     * 检查参数
     */
    private fun checkArgs() {
        with(userName) {
            addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
                override fun afterTextChanged(s: Editable) {
                    val userNameVal = text.toString()
                    userNameVal.ifEmpty { error = "请输入用户名" }
                }
            })
        }

        with(passWord) {
            addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(
                    s: CharSequence,
                    start: Int,
                    count: Int,
                    after: Int
                ) {
                }

                override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}

                override fun afterTextChanged(s: Editable) {
                    val passWordVal = text.toString()

                    if (TextUtils.isEmpty(passWordVal) && "" == passWordVal) {
                        error = "请输入密码"
                    }
                    if (passWordVal.length !in 6..12) {
                        error = "请输入6-12位数的英文字母与数字的组合"
                    }
                }
            })
        }
    }


    /**
     * LiveData 观察
     */
    private fun observe() {
        if (!viewModel.responseData.hasObservers()) {
            viewModel.responseData.observe(this, Observer { result ->
                val response = result.getOrNull()
                if (response == null) {
                    ResponseHandler.getFailureTips(result.exceptionOrNull()).showToast()
                    return@Observer
                }

                //response.code?.takeIf { it!=-1 }?
                if (response.code == -1) {
                    Toast.makeText(this, response.msg, Toast.LENGTH_SHORT).show()
                    return@Observer
                }

                //找不到就插一条数据进数据库,类似电话号码自动注册.
                val userModel = UserDao().getOne(userName.text.toString())

                //如果为null保存
                if (userModel == null) {
                    val ret = UserDao().save(
                        UserModel(
                            userName = userName.text.toString(),
                            passWord = passWord.text.toString(),
                            createDate = Date()
                        ), false
                    )
                    //if为真打印
                    takeIf { ret }?.apply { logI(TAG, "保存用户${userName.text}成功！") }
                }

                Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
            })
        }

    }


    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.iv_eye -> {
                if (isHideFirst) {
                    imageView?.setImageResource(R.drawable.show_eye)
                    //密文
                    passWord.transformationMethod = HideReturnsTransformationMethod.getInstance()
                    isHideFirst = false
                } else {
                    imageView?.setImageResource(R.drawable.hide_eye)
                    //密文
                    passWord.transformationMethod = PasswordTransformationMethod.getInstance()
                    isHideFirst = true

                }
                // 光标的位置
                val index = passWord.text.toString().length
                passWord.setSelection(index)
            }
        }

    }

    companion object {
        private val TAG by lazy { javaClass.simpleName }


    }
}